package com.bookstore.filter;

import com.bookstore.entity.User;
import com.bookstore.utils.DataConsts;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = {"/admin/*"})
public class PermissionFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        String URL = request.getRequestURL().toString();


        //session中的user不为空 且是管理员身份
        if (user != null && user.getRole().equals(DataConsts.USER_ROLE_SUPER)) {
            chain.doFilter(req, resp);
        } else if (URL.endsWith("user.do") || URL.endsWith("login.html")) {
            //在这个if判断中 维护白名单 不至于所有的请求都被拦截
            chain.doFilter(req, resp);
        } else {
            response.sendRedirect(request.getContextPath() + "/admin/login.html");
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
